 
var dialogJobId;
var rateTableType;
var globalRateTableId;
var currentActionID;
function getRateTableId(entityUserID,jobId,type, qglJobTypeNew, userInputCode){
	
	
	showProcessingDialog();
	 
	$.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'rate-template.action?getRateTableId',//name of action?name of method in action
		  dataType: 'json',
		  data: {entityUserId:entityUserID},
			 
		  success: function(result){
			  if(result!=null){
				  if(result != null && result>0)
				  showRateTable(result, qglJobTypeNew, userInputCode);
				  dialogJobId = jobId;
				  rateTableType = type;
				  globalRateTableId = result;
				  setSelectedRateItem();
				  initgetMasterRateTable=false;
				 
				}
	     
			 },
			  error:function() { 
				  
			  }
		});
 
}

function createNewAgencyRateItem(userInputCode,ratetable, qglJobTypeNew){
	var tableRowElem=$(ratetable).find(".code-name");
	var emptyRow=false;
	$(tableRowElem).each(function(){
		if($(this).val()==""){
			emptyRow=true;
			
			$(this).closest("tr").find(".rtindexcheck").attr("checked", true);
			if(!qglJobTypeNew){
				$.each(masterRateItemsARArray, function(index, value){
            		if(value["codeName"].toLowerCase()==userInputCode.toLowerCase()){
            			$(this).val(value["codeName"]);
            			$(this).closest("tr").find("#des").val(value["description"]);
            			$(this).closest("tr").find("#perUnitId").val(value["priceType"]);
            			$(this).closest("tr").find("#unitId").val(value["unitType"]);
            			$(this).closest("tr").find("#priceVal").val(0);
            		}
            	});
			}
			else
				$(this).val(userInputCode);
		}
	});
	if(!emptyRow){
		$(ratetable).closest("#rateTableFormId").find("#idAddRateItem").trigger("click");
		$(ratetable).find(".code-name:first").closest("tr").find(".rtindexcheck").attr("checked", true);
		if(!qglJobTypeNew){
			$.each(masterRateItemsARArray, function(index, value){
        		if(value["codeName"].toLowerCase()==userInputCode.toLowerCase()){
        			
        			$(ratetable).find(".code-name:first").val(value["codeName"]);
        			$(ratetable).find("#des:first").val(value["description"]);
        			$(ratetable).find("#perUnitId:first").val(value["priceType"]);
        			$(ratetable).find("#unitId:first").val(value["unitType"]);
        			$(ratetable).find("#priceVal:first").val(0);
        		}
        	});
		}
		else
			$(ratetable).find(".code-name:first").val(userInputCode);

	}
	
	
}
function showRateTable(rateTableId, qglJobTypeNew, userInputCode){
		params = {rateId:rateTableId,
	    		purpose:'QGL'};
	          
	    $.post('rate-template.action?showRateTableForQGL',
	    		params,
	            function (result) {
	    	$('.processImage').dialog('close');
	    	$( "#rateTableForm" ).dialog({
	    	        autoOpen: true,
	    	        height: 500,
	    	        width: 950,
	    	        modal: true,
	    	        close: function() {
 	    	           $("#rateTableForm").html("");
					    currentActionID = 0;
 	    	          dialogJobId = null;
 	    	         rateTableType = null;
 	    	        globalRateTableId = null; 
 	    	        
 	    	       // alert("currentAction1"+currentAction1)
 	    	       currentAction = currentAction1;
 	    	        },
 	    	       open:function(){
	    				$(".ui-button").addClass("ui-state-default");	
 						setTimeout(function(){
							$(".rateTableInfoContentContainer").hide();
							$(".rateTableSlidebuttonDiv").hide();
							$(".rateTableInfoBut").hide();
							//$(".infoBut").hide();

							$(".qglRateTblInfoContentContainer").show();
							$(".qglRateTblSlidebuttonDiv").show();
							$(".qglRateTblInfoBut").show();
							
	 						$("#rateItemTable").attr("tabindex","0");
	 						$("#rateItemTable").focus();
	 						$("#rateItemTable").removeAttr("tabindex");
	 						if(qglJobTypeNew){
	 							createNewAgencyRateItem(userInputCode,"#rateItemTable", true); 						
	 						}
	 						else{
	 							createNewAgencyRateItem(userInputCode,"#rateItemTable", false, masterRateItemsArray);
	 						}
 						},100);
 					},
 	    	        buttons:{
						"Apply Rate Code To Job":function(){

						$("#applybutton").trigger("click");
						},

 	    	        	"Close":function(){
 	    	        		currentActionID = 0;
 	    	        		isRateTableChaned = false;
 	    	       		    isFormFieldChanged = false;
 	    	        		
 	    	        		$(this).dialog('close');
 	    	        	}
 	    	        },
 	    	       create:function () {
				        $(this).closest(".ui-dialog")
				            .find(".ui-button") ;// the first button
				           // .addClass("p-button");
				    }
	    	 });
	    	        $("#rateTableForm").html(result);
	    	        setSelectedRateItem();
	    	        hideCategory();
	    	        
	            });
	 
}
function saveRateTableFromQGL(){
		
	$("#ui-tips").text("").removeClass("ui-state-highlight");

$(".mandatoryfield").RateTableCustomValidator("required",true,this);
var isPopup=true;
retflag= validateRateTable();

if(retflag)
retflag = checkPayPeriodDuplicates();

if(retflag)
retflag =checkForJobStartDate(isPopup);

if(retflag)
$(".numberVal").RateTableCustomValidatorNum("number",true,this);

if(retflag)
$(".urlinput").RateTableCustomValidatorurl("url",true,this);

if(retflag)
$(".emailval").RateTableCustomValidatoremail("email",true,this);

if(retflag)
$("#zip").RateTableCustomValidatorZip("zip",true,this);

if(retflag)
$("#mainPhone").RateTableCustomValidatorPhone("Phone",true,this);

if(retflag)
	retflag = checkProfileCategoryDetails(isPopup);

flag=retflag;

if(flag){
callAjaxSaveQGLRateTable();
}

}

function callAjaxSaveQGLRateTable(){
	$.ajaxSetup({
	   jsonp: null,
	   jsonpCallback: null
	});

    $.ajax({
	  type:'POST',
	  url: 'rate-template.action?saveFromQGL',//name of action?name of method in action
	  dataType: 'json',
	  data: $("#rateTableFormId").serialize(),
		 
	  success: function(result){
		  	$('.processImage').dialog("close");
			  if(result != null){
				 showRateTable(globalRateTableId);
				 setSelectedRateItem();
			 	 alert("successfully saved");
			  }
			  else{
				  alert("failure");
			  }
		 	},
		  error:function() { 
			  
		  }
	}); 
}
function saveAndMapRateTableFromQGL(rateTableId){
 	var isMandatory = validateRateTable();
 	var singleSelected = validateMultipleRateItemsMapping();
 	 var expdateval = false;
 	if(singleSelected){
 		expdateval = checkExpdateCondition();
 	}
 	   
    if(!isMandatory || !singleSelected || expdateval){
    	
    	return false;
    }
    else{
    	 if(checkCCCondition())
		 return false;
	 $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'rate-template.action?mapJobToRateItem',//name of action?name of method in action
		  dataType: 'json',
		  data: $("#rateTableFormId").serialize()+'&jobId='+dialogJobId+'&mapJobToRateItem=true',
			 
		  success: function(result){
 			  if(result>0){
				 
			$("#rate-item-success-div").text("The selected Rate Code has been applied for this Job").addClass("alert alert-success");
			
				  setRateIdsToJob(result);
				  setTimeout(closeDialog,2000) 
			 /*		showRateTable(globalRateTableId);
					setSelectedRateItem();
					rateitemerrdiv.innerHTML = str;*/
			 }
			  else{
				  alert("failure");
			  }
	     
			 },
			  error:function() { 
				  
			  }
		}); 
    	
    
    }
}

function closeDialog(){
	
	$( "#rateTableForm" ).dialog('close');
	
	
}


function setRateIdsToJob(rateItemId){
	if(rateTableType=='AGENCY')
		$("#typeId"+dialogJobId).val(rateItemId);
	else if(rateTableType == 'SCOPIST')
		$("#scopistRateId"+dialogJobId).val(rateItemId);
	else if(rateTableType == 'PROOFER')
		$("#prooferRateId"+dialogJobId).val(rateItemId);
	
	if($("#typeId"+dialogJobId).closest(".job-record-block").find(".total-ar").length>0)
		callAjaxToCalculatePaymentAferJobSaving(dialogJobId);
	
}


function validateMultipleRateItemsMapping(){
	 
 	 var count = 0;
 	 var singleSelected = true;
 	$("#rate-item-qgl-err-div").text("").removeClass("ui-state-highlight");
 	$("#rate-item-qgl-err-div-bottom").text("").removeClass("ui-state-highlight");
	  $(".userRateItems tbody tr").each(function() {
		  //console.log($(this).find(".rtindexcheck:checked").val());
 	 		if($(this).find(".rtindexcheck:checked").val()){ 
 	 			++count;
	  		}
  	 		
	 		
 	  });
	  if(count>1){
		  	
		  	if(rateTableType=='AGENCY'){
		  		$("#rate-item-qgl-err-div").text( "You cannot assign more than one TYPE code to a job. Add additional codes in Services/Expenses.").addClass( "ui-state-highlight").css("margin", "65px 0 0");
		  		$("#rate-item-qgl-err-div-bottom").text( "You cannot assign more than one TYPE code to a job. Add additional codes in Services/Expenses.").addClass( "ui-state-highlight");
	  		}
	  		else{
	  			$("#rate-item-qgl-err-div").text( "You can assign only one code to A/P.").addClass( "ui-state-highlight").css("margin", "65px 0 0");
		  		$("#rate-item-qgl-err-div-bottom").text( "You can assign only one code to A/P.").addClass( "ui-state-highlight");
	  		}
	    	singleSelected = false;
			
	  }
		
	  if(count<1){
		   
	    	$("#rate-item-qgl-err-div").text("Please select a code to assign to this Job.").addClass( "ui-state-highlight").css("margin", "65px 0 0");
	    	$("#rate-item-qgl-err-div-bottom").text("Please select a code to assign to this Job.").addClass( "ui-state-highlight");
 	    	singleSelected = false;
	  }
	  if(count == 1 && rateTableType=='AGENCY'){
  		  $(".userRateItems tbody tr").each(function() {
	 	 		if($(this).find(".rtindexcheck:checked").val()){ 
	 	 			if($(this).find("#rateItemCode > input").val()==""){
	 	 				$("#rate-item-qgl-err-div").text("Please enter value for the code").addClass( "ui-state-highlight").css("margin", "65px 0 0");
	 	 		    	$("#rate-item-qgl-err-div-bottom").text("Please enter value for the code").addClass( "ui-state-highlight");
	 	 	 	    	singleSelected = false;
	 	 			}
	 	 			else{
	 	 				if(!(checkExpdateCondition()) && !(checkCCCondition())){
							$("#typeId"+dialogJobId).next().html($(this).find("#rateItemCode > input").val());
		 	 	 			$("#typeId"+dialogJobId).next().next().val($(this).find("#rateItemCode > input").val());
							$("#agencylink"+dialogJobId).attr("title","Agency Rate Code: "+$(this).find("#rateItemCode > input").val()+", click the hyperlink to go to A/R Rate table");
							//For qgl-log-pending-turnedInPage
							$(".agencylink"+dialogJobId).attr("title","Agency Rate Code: "+$(this).find("#rateItemCode > input").val()+", click the hyperlink to go to A/R Rate table");
	 	 				}
	 	 			}	 	 	 			
	 	 		}
	 	  });
	  }
	  if(count == 1 ){
  		  $(".userRateItems tbody tr").each(function() {
	 	 		if($(this).find(".rtindexcheck:checked").val()){ 
	 	 			if($.trim($(this).find("#rateItemCode > input").val()).length == 0){
	 	 				$("#rate-item-qgl-err-div").text("Please enter value for the code").addClass( "ui-state-highlight").css("margin", "65px 0 0");
	 	 		    	$("#rate-item-qgl-err-div-bottom").text("Please enter value for the code").addClass( "ui-state-highlight");
	 	 	 	    	singleSelected = false;
	 	 			}
					else 
					{
						if(rateTableType=='SCOPIST' && !(checkExpdateCondition()))
						{
						   $("#scopistlink"+dialogJobId).attr("title","Scopist Rate Code: "+$(this).find("#rateItemCode > input").val()+", click the hyperlink to go to A/P Rate table");
						   //For qgl-log-pending-turnedInPage
						   $(".scopistlink"+dialogJobId).attr("title","Scopist Rate Code: "+$(this).find("#rateItemCode > input").val()+", click the hyperlink to go to A/P Rate table");
						}
						 
						if(rateTableType=='PROOFER' && !(checkExpdateCondition()))
						{
							$("#prooferlink"+dialogJobId).attr("title","Proofer Rate Code: "+$(this).find("#rateItemCode > input").val()+", click the hyperlink to go to A/P Rate table");
							//For qgl-log-pending-turnedInPage
							$(".prooferlink"+dialogJobId).attr("title","Proofer Rate Code: "+$(this).find("#rateItemCode > input").val()+", click the hyperlink to go to A/P Rate table");
						}
					}
	 	 		}
	 	  });
	  }
	  return singleSelected;
}
function checkCCCondition(){
var ccpresent = false;
	$("#rate-item-qgl-err-div").text("").removeClass("ui-state-highlight");
	$("#rate-item-qgl-err-div-bottom").text("").removeClass("ui-state-highlight");
	  $(".userRateItems tbody tr").each(function() {
		  //console.log($(this).find(".rtindexcheck:checked").val());
	 		if($(this).find(".rtindexcheck:checked").val()){ 
	 			var ccval = $(this).closest("tr").find(".code-name").val();
	 			var ccvalcheck=ccval.toUpperCase();
				if(ccvalcheck=="CC")
					ccpresent = true;
				
	  		}
	 		
	 		
	  });
	  if(ccpresent)
		{
		  $("#rate-item-qgl-err-div").text( "You cannot select CC as Rate Code.").addClass( "ui-state-highlight").css("margin", "65px 0 0");
	    	$("#rate-item-qgl-err-div-bottom").text( "You cannot select CC as Rate Code.").addClass( "ui-state-highlight");
		}
	  return ccpresent;
}
function checkExpdateCondition(){
	
	 var expdatepresent = false;
	$("#rate-item-qgl-err-div").text("").removeClass("ui-state-highlight");
	$("#rate-item-qgl-err-div-bottom").text("").removeClass("ui-state-highlight");
	  $(".userRateItems tbody tr").each(function() {
		  //console.log($(this).find(".rtindexcheck:checked").val());
	 		if($(this).find(".rtindexcheck:checked").val()){ 
	 			var reqval = $(this).closest("tr").find(".price-type-id option:selected").val();
	 			if(reqval == 2)
	 				expdatepresent = true;
	  		}
	 		
	 		
	  });
	  if(expdatepresent)
		{
		  $("#rate-item-qgl-err-div").text( "You cannot select Expedite as Rate Code.").addClass( "ui-state-highlight").css("margin", "65px 0 0");
	    	$("#rate-item-qgl-err-div-bottom").text( "You cannot select Expedite as Rate Code.").addClass( "ui-state-highlight");
		}
	  return expdatepresent;
}

function setSelectedRateItem(){
	var rateItemIdVal = 0;
	if(rateTableType == 'AGENCY')
		rateItemIdVal = $("#typeId"+dialogJobId).val();
	else if(rateTableType == 'SCOPIST')
		rateItemIdVal = $("#scopistRateId"+dialogJobId).val();
	else if(rateTableType == 'PROOFER')
		rateItemIdVal = $("#prooferRateId"+dialogJobId).val();
	$(".userRateItems tbody tr").each(function() {
			idVal = $(this).find(".rtindexcheck").attr("id");
			 
			if($("#rateItemId"+idVal).val() == rateItemIdVal){ 
				$(this).find(".rtindexcheck").val(true).attr("checked","checked");
			}
	});
}

function showProcessingDialog(){
	$('.processImage').html("Please wait while your request is in process...<img src='images/billing-invoice/search.gif' style='float:right;' alt='AjaxImage' width='22' height='22'/> ");
	$('.processImage').dialog({
		
		title:"Processing your request"
		
	});
	
}

function hideCategory(){

	//$("#profileCategory").attr("disabled", "disabled");
	//$("#profileType").attr("disabled", "disabled");

}